// pages/topicality/jiancejigou/jiancejigou.js
const app = getApp()
const util = require("../../../utils/util.js");
var QQMapWX = require('../../../utils/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min.js');
var qqmapsdk = new QQMapWX({
  key: 'KR7BZ-XSQ3P-VGFD7-LNRZL-E7PXE-STF76'
});
Page({

  /**
   * 页面的初始数据
   */
  data: {
    city: '深圳',
    cityCode: 'sz',
    showModalStatus: false,
    resultArr: [],
    inputValue: '', //输入框输入值
    page: 0, //页数,从第0页开始
    totalNum: 0, //总条数
    hasMore: false, //是否有更多
    preValue: '', //预输入的value值
    //当前定位位置
    latitude: null,
    longitude: null,
    quArr: [],
    quIndex: 0,
    jigouArr: ['全部机构', '可供预约'],
    jigouIndex: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    util.getUrl(app.globalData.url).then(async e => {
      ks.getLocation({
        type: 'gcj02',
        success: async (res) => {
          this.setData({
            latitude: res.latitude,
            longitude: res.longitude,
          })
          // 如果携带有城市和搜索参数
          if (options.city && options.content) {
            // 如果不带城市参数，获取定位
            if (!options.city) {
              this.getLocation()
            } else {
              this.setData({
                city: options.city,
                cityCode: await this.getCityCode(options.city),
                inputValue: options.content,
                preValue: options.content
              })
              this.selectComponent("#fangyiTools").getTools(this.data.cityCode)
              this.getqu()
              this.search()
            }
          } else { //没有携带参数进入页面
            this.getLocation()
            this.selectComponent("#fangyiTools").getTools(this.data.cityCode)
            this.getqu()
            this.render()
          }
        }
      })
    })
  },

  // 获取定位
  getLocation() {
    qqmapsdk.reverseGeocoder({
      success: (res) => {
        let city = res.result.address_component.city;
        if (city && !city.includes(this.data.city)) {
          ks.showModal({
            content: '您当前定位城市为' + city + '\n是否需要切换到' + city + '检测机构查询？',
            success: async res => {
              if (res.confirm) {
                city = city.substr(0, city.length - 1);
                const cityCode = await this.getCityCode(city)
                this.setData({
                  city,
                  cityCode,
                  resultArr: [],
                  page: 0,
                })
                this.getqu()
                this.render()
                this.selectComponent("#fangyiTools").getTools(this.data.cityCode)
              }
            }
          })
        }
      }
    })
  },
  // 获取cityCode,参数为市
  async getCityCode(city) {
    const res = await util.request("citycode.php", {
      action: "city",
      city: city
    }, "POST")

    return res.data.data[0].citycode
  },
  // 确定选择城市
  chooseCity(e) {
    this.setData({
      city: e.detail.city,
      cityCode: e.detail.cityCode,
      resultArr: [],
      page: 0,
      quIndex: 0,
      jigouIndex: 0
    })
    this.selectComponent("#fangyiTools").getTools(this.data.cityCode)
    this.getqu()
    this.render()
  },
  //通过cityCode获取区
  getqu() {
    util.request('zhuanti.php', {
      action: 'get_qu',
      citycode: this.data.cityCode
    }).then(e => {
      let quArr = e.data.data
      quArr.unshift({
        qu: '全部区域'
      })
      this.setData({
        quArr
      })

    })
  },
  // 渲染页面
  render(keywords, offset, qu) {
    util.request('zhuanti.php', {
      action: "jcdidian",
      citycode: this.data.cityCode,
      keywords: keywords || '',
      offset: offset || 0,
      limit: 5,
      qu: this.data.quIndex == 0 ? '' : this.data.quArr[this.data.quIndex].qu, //是否选择全部区域
      jg: parseInt(this.data.jigouIndex) + 1
    }, 'POST').then(e => {
      
      const list = e.data.data.list
      if (list) {
        if (this.data.latitude && this.data.longitude) {
          list.forEach((item) => {
            const distance = this.getDistance(this.data.latitude, this.data.longitude, item.lat, item.lon)
            item.distance = distance
          })
        }
        this.setData({
          resultArr: this.data.resultArr.concat(list),
          totalNum: e.data.data.count.c,
          hasMore: true
        })
        if (this.data.resultArr.length >= this.data.totalNum) {
          this.setData({
            hasMore: false
          })
          return
        }
      } else {
        this.setData({
          hasMore: false,
          totalNum: 0
        })
      }
    })
  },
  //改变选择机构
  changejigou(e) {
    this.setData({
      jigouIndex: e.detail.value,
      resultArr: [],
      page: 0
    })
    this.render()
  },
  changequ(e) {
    this.setData({
      quIndex: e.detail.value,
      resultArr: [],
      page: 0
    })
    this.render()
  },
  // 输入框赋值
  input(e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  // 搜索
  search() {
    if (this.data.inputValue.trim()) {
      this.setData({
        resultArr: [],
        page: 0
      })
      this.render(this.data.inputValue, 0)
    } else {
      ks.showToast({
        title: '请输入想要查询的地区',
        icon: 'none'
      })
    }

  },
  // 查看更多
  more() {
    this.setData({
      page: this.data.page + 1
    })
    this.render(this.data.inputValue, this.data.page * 5)
  },

  // 拨打电话
  dealPhone(e) {
    ks.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone
    })
  },
  goMap(e) {
    util.navContact('ss', 'https://ditu.so.com/?t=map&src=bendibao&k=' + e.currentTarget.dataset.name + '&city=' + this.data.city)
  },
  goyuyue(e) {
    util.navContact('ss', e.currentTarget.dataset.url)
  },
  // 
  toHome() {
    ks.navigateTo({
      url: '/pages/topicality/hesuanjiance/hesuanjiance?city=' + this.data.city,
    })
  },
  //进行经纬度转换为距离的计算
  getDistance: function (lon1, lat1, lon2, lat2) {

    if (lon2 && lat2) {

      var radLat1 = lat1 * Math.PI / 180.0;

      var radLat2 = lat2 * Math.PI / 180.0;

      var a = radLat1 - radLat2;

      var b = lon1 * Math.PI / 180.0 - lon2 * Math.PI / 180.0;

      var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +

        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));

      s = s * 6378.137; // EARTH_RADIUS;

      s = Math.round(s * 10000) / 10000;

      s = s.toFixed(1)
      return s + 'km';
    } else {
      return false
    }

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '各地核酸检测机构查询'
    }
  }
})